package com.atguigu.gulimall.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuElasticSearchModleTO;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.BrandVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.ParsedAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        //动态构建出查询需要的DSL语句
        SearchResult result = null;
        //1准备检索请求

        //构建检索请求
        SearchRequest request = buildSearchRequest(param);

        try {
            //2:执行检索请求
            SearchResponse response = client.search(request, GulimallElasticSearchConfig.COMMON_OPTIONS);
            //3:分析响应数据,封装我们需要的响应格式
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }

    /**
     * 构建检索请求:
     * 模糊匹配,过滤(按属性,分类,品牌,价格区间,库存),排序,分页,高亮,聚合分析
     **/
    private SearchRequest buildSearchRequest(SearchParam param) {

        //构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 模糊匹配,过滤(按属性,分类,品牌,价格区间,库存)
         **/
        //1:构建bool-queryn
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1:must:模糊匹配
        String keyWord = param.getKeyWord();
        if (!StringUtils.isEmpty(keyWord)) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", keyWord));
        }
        //1.2:filter
        if (param.getCatelogId() != null) {
            //按照三级分类Id查询
            boolQuery.filter(QueryBuilders.termQuery("catelogId", param.getCatelogId()));
        }

        if (!CollectionUtils.isEmpty(param.getBrandId())) {
            //按照品牌ID查询
            boolQuery.filter(QueryBuilders.termQuery("brandId", param.getBrandId()));
        }

        //按照所有属性进行查询
        if (!CollectionUtils.isEmpty(param.getAttrs())) {

            for (String attrStr : param.getAttrs()) {
                //嵌入式查询条件构造
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                //需要检索的属性ID
                String attrId = s[0];
                //需要检索的属性值
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrValue", attrValues));

                //每一个必须生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attr", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }

        }

        //按照是否有库存进行查询
        if (!StringUtils.isEmpty(param.getHasStock())) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        //按照价格区间构建查询条件
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");

            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }

            boolQuery.filter(rangeQuery);
        }
        /**
         * 把以前的所有条件都拿来进行封装
         **/
        sourceBuilder.query(boolQuery);

        /**
         * 排序,分页,高亮
         **/
        //2.1:排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        //2.2:分页
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2.3:高亮
        if (!StringUtils.isEmpty(param.getKeyWord())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
        }

        /**
         * 聚合分析
         **/
        //1:品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        //品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);

        //分类聚合
        TermsAggregationBuilder cateLogAgg = AggregationBuilders.terms("catelog_agg").field("catelogId").size(50);
        //分类聚合的子聚合
        cateLogAgg.subAggregation(AggregationBuilders.terms("catelog_agg")).field("catelogName").size(1);
        sourceBuilder.aggregation(cateLogAgg);
        //属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        //1):attrAgg嵌入式聚合
        //聚合当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(1);
        //1.1)attr_id_agg里面还有两个子聚合
        //聚合分析出当前attrId对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出当前attrId对应的所有可能的属性值attrValue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1));

        attrAgg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attrAgg);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return searchRequest;
    }

    /**
     * 构建结果数据
     **/
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {

        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
        List<SkuElasticSearchModleTO> list = new ArrayList();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuElasticSearchModleTO modleTO = JSON.parseObject(sourceAsString, SkuElasticSearchModleTO.class);
                //高亮显示关键字
                if (!StringUtils.isEmpty(param.getKeyWord())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.fragments()[0].string();
                    modleTO.setSkuTitle(string);
                }
                list.add(modleTO);
            }
        }
        //1:返回的所有查询到的商品
        result.setProduct(list);

        //2:当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性ID
            Long attrId = bucket.getKeyAsNumber().longValue();
            //得到属性名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("arrt_name_agg")).getBuckets().get(0).getKeyAsString();
            //得到属性的所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                return ((Terms.Bucket) item).getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        //3:当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //1):得到品牌的ID
            long brandId = bucket.getKeyAsNumber().longValue();
            //2):得到品牌的名字
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            //3):得到品牌的图片地址
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        //4:当前商品涉及到的所有分类信息
        ParsedLongTerms catelogAgg = response.getAggregations().get("catelog_agg");
        List<? extends Terms.Bucket> buckets = catelogAgg.getBuckets();
        List<SearchResult.CatalogVo> catalogVos = new ArrayList();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类ID
            String key = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(key));
            //得到分类名字,就要从bucket里面的子聚合获取
            ParsedStringTerms catelogNameAgg = bucket.getAggregations().get("catelog_name_agg");
            String catelogName = catelogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catelogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        //5:分页信息-总记录数
        long total = hits.getTotalHits();
        result.setTotal(total);

        //6:分页信息-总页码
        int totalPages = (int) (total % EsConstant.PRODUCT_PAGESIZE == 0 ? total / EsConstant.PRODUCT_PAGESIZE : total / EsConstant.PRODUCT_PAGESIZE + 1);
        result.setTotalPages(total);

        //7:分页信息-当前页码
        result.setPageNum(param.getPageNum());

        List<Integer> pageNavs = new ArrayList();
        for (int i = 0; i < totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        if (!CollectionUtils.isEmpty(param.getAttrs())){
            //8:构建面包屑导航功能
            List<SearchResult.NasVo> collect = param.getAttrs().stream().map(attr -> {
                SearchResult.NasVo nasVo = new SearchResult.NasVo();
                String[] s = attr.split("_");
                nasVo.setNasValue(s[1]);
                R r = productFeignService.info(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getDate("attr", new TypeReference<AttrResponseVo>() {
                    });
                    nasVo.setNasName(data.getAttrName());
                } else {
                    nasVo.setNasName(s[0]);
                }

                //取消了这个面包屑以后,我们要跳转的那个地方,将请求地址的URL里面的当前条件置空
                //拿到当前的所有条件,去掉当前,中文要进行编码
                String replace = getString(param, attr,"attrs");
                nasVo.setLink("当前自己网页的地址加上接口路径" + replace);
                return nasVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);

            //品牌,分类也有面包屑
            if (!CollectionUtils.isEmpty(param.getBrandId())){
                List<SearchResult.NasVo> navs = result.getNavs();
                SearchResult.NasVo nasVo = new SearchResult.NasVo();
                nasVo.setNasName("品牌");
                //远程查询所有品牌
                R r = productFeignService.getBrandsByIds(param.getBrandId());
                if (r.getCode() == 0){
                    List<BrandVo> brandVo = r.getDate("brand", new TypeReference<List<BrandVo>>() {
                    });
                    StringBuffer buffer = new StringBuffer();
                    String replace = null;
                    for (BrandVo vo : brandVo) {
                        buffer.append(vo.getName() + ";");
                        replace = getString(param, vo.getBrandId() +"","brandId");
                    }
                    nasVo.setNasValue(buffer.toString());
                    nasVo.setLink("当前自己网页的地址加上接口路径" + replace);
                }
                navs.add(nasVo);
                result.setNavs(navs);
            }
        }

        return result;
    }

    private String getString(SearchParam param, String value,String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            //浏览器对空格编码和Java不一样
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace(key + encode, "");
    }

}
